package cn.edu.scau.cmi.zhuanglinting.hibernate.DAO;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.luyicheng.hibernate.domain.Student;

public class StudentDAO {

	private static Configuration configuration;

	private static SessionFactory factory;

	private static Session session;

	static {
		configuration = new Configuration();
		// configuration.configure().addClass(User.class);
		configuration.configure();
		factory = configuration.buildSessionFactory();
	}

	public Student findStudentById(int id) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		Student student = session.get(Student.class, id);
		transaction.commit();
		session.close();
		return student;
	}

	public List<Student> findStudentByName(String name) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		Query query = session.createQuery("FROM Student Where name = ?1");
		query.setParameter(1, name);
		List<Student> list = query.list();
		transaction.commit();
		session.close();
		return list;
	}

	public void newStudent(Student student) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.save(student);
		transaction.commit();
		session.close();
	}

	public void updateStudent(Student student) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.update(student);
		transaction.commit();
		session.close();
	}

	public List<Student> findAllStudent() {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		Query query = session.createQuery("FROM Student");
		List<Student> list = query.list();
		transaction.commit();
		session.close();
		return list;
	}

	public void deleteStudent(Student student) {
		session = factory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.delete(student);
		transaction.commit();
		session.close();
	}
}

